// components/lyric/lyric.js
// 当前歌词高度
let lyricHeight = 0
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    showLyric: {
      type: Boolean,
      value: false
    },
    lyric: String
  },
  observers: {
    lyric(lrc) {
      // console.log(lrc)
      if(lrc == '暂无歌词'){
        this.setData({
          lrcList: [
            {
              lrc,
              time: 0
            }
          ],
          nowLyricIndex: -1
        })
      }else{
        this._parseLyric(lrc)
      }
     
    }
  },
  /**
   * 组件的初始数据
   */
  data: {
    lrcList: [],
    // 当前选中歌词索引
    nowLyricIndex: 0,
    // 滚动条滚动高度
    scrollTop: 0
  },
  lifetimes: {
    ready() {
      // px rpx 进行换算
      wx.getSystemInfo({
        success(res){
          console.log(res)
          // 求出 1rpx 大小 * 64 = 当前屏幕下一行歌词对应高度
          lyricHeight = res.screenWidth / 750 * 64
        },
      })
    }
  },
  /**
   * 组件的方法列表
   */
  methods: {
    // 更新歌词
    update(currentTime) {
      // console.log(lrcList)
      // console.log(currentTime)
      let lrcList = this.data.lrcList
      if(lrcList.length == 0) return
      // 时长大于歌词长度 优化
      if (currentTime > lrcList[lrcList.length - 1].time){
        if(this.data.nowLyricIndex != -1){
          this.setData({
            nowLyricIndex: -1,
            scrollTop: lrcList.length * lyricHeight
          })
        }
      }

      // 同步歌词滚动
      for(let i = 0, len = lrcList.length; i < len; i++){
        if(currentTime <= lrcList[i].time){
          this.setData({
            nowLyricIndex: i - 1,
            scrollTop: (i-1) * lyricHeight
          })
          break
        }
      }
    },
    _parseLyric(sLyric) {
      let line = sLyric.split('\n')
      let _lrcList = []
      line.forEach((elem) => {
        let time = elem.match(/\[(\d{2,}):(\d{2})(?:\.(\d{2,3}))?]/g)
        if(time != null) {
          // console.log(time)
          let lrc = elem.split(time)[1]
          let timeReg = time[0].match(/(\d{2,}):(\d{2})(?:\.(\d{2,3}))?/)
          // console.log(timeReg)
          // 时间转换为秒
          let time2seconds = parseInt(timeReg[1]) * 60 + parseInt(timeReg[2]) + parseInt(timeReg[3]) / 1000
          _lrcList.push({
            lrc,
            time: time2seconds,
          })
          // console.log(_lrcList)
        }
      })

      this.setData({
        lrcList: _lrcList
      })
    }
  }
})
